<?php

namespace app\common\model\wechat;

use app\common\model\BaseModel;
use app\common\model\wechat\tralts\WechatCreateCoupon;


class WechatCoupon extends BaseModel
{

    public $coupon = [];
    protected $plaid;
    protected $addon;
    public $type_names = array(
        1 => "核销券",
        2 => "现金券",
        3 => "折扣券"
    );

    protected $type = [
        'config' => 'json',
        'place'  => 'json'
    ];

    use WechatCreateCoupon;

    public function __construct(array $data = [])
    {
        parent::__construct($data);
        $this->plaid = get_plaid();
        $this->addon = get_addon();
    }

    //创建方法
    // 1、直接创建
    public function createUserCoupon($coupon, $user_id)
    {
        $data = array(
            ...$coupon,
            'uid'   => $user_id,
            'plaid' => $this->plaid,
            'addon' => $this->addon
        );
    }


    //获取方法
    // 1、单条获取


    // 2、多条获取
    /**
     * 获取用户的多条卡券
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCouponUserList($uid)
    {
        $page = input('page', 1);
        $size = input('size', 10);
        $screenData = input('screenData', []);
        $where[] = ['uid', '=', $uid];
        if ($screenData['type'] > 0) {
            $where[] = ['end_time', '>', time()];
            $where[] = ['type', '=', $screenData['type']];
        } elseif ($screenData['type'] == 0) {
            $where[] = ['end_time', '>', time()];
        } elseif ($screenData['type'] == -1) {
            $where[] = ['end_time', '<', time()];
        }
        if ($screenData['sort'] == 0) {
            $order = 'id DESC';
        } elseif ($screenData['sort'] == 1) {
            $order = 'end_time asc';
        }
        $list = $this->where($where)->order($order)->limit($size)->page($page)->select();
        $count = $this->where($where)->count();
        return ['count' => $count, 'list' => $list];
    }
    //删除方法
    /*******************核销**************************/
    //核销方法
    public function checkCoupon($key)
    {
        $user = getWxUser();
        $coupon = $this->where(['key' => $key, 'check_uid' => $user['id']])->find();
        $check = $this->checkCouponStatus($coupon);
        if ($check['code'] == -1) return $check;
        $new_number = $coupon['number'] > 0 ? $coupon['number'] - 1 : 0;
        $update_data = array(
            'number'     => $new_number,
            'check_time' => time(),
            'check_uid'  => $user['id']
        );
        if ($new_number == 0) {
            $update_data['state'] = 1;
        }
        $this->where(['id' => $coupon['id']])->save($update_data);
        return ['code' => 0, 'msg' => '核销成功'];
    }


    /**
     * 核销卡券列表
     * @param $check_uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCheckCouponUserList($check_uid)
    {
        $page = input('page', 1);
        $size = input('size', 10);
        $screenData = input('screenData', []);
        $where[] = ['check_uid', '=', $check_uid];
        $where[] = ['type', '=', 1];

        switch ($screenData['active']) {
            case 0:
                $where[] = ['state', '=', 0];
                $where[] = ['end_time', '>=', time()];
                break;
            case 1:
                $where[] = ['state', '=', 1];
                break;
            case 2:
                $where[] = ['state', '=', 0];
                $where[] = ['end_time', '<', time()];
                break;
        }

        if ($screenData['sort'] == 0) {
            $order = 'id DESC';
        } elseif ($screenData['sort'] == 1) {
            $order = 'end_time asc';
        }
        $list = $this->where($where)->order($order)->limit($size)->page($page)->select();
        foreach ($list as $key => $value) {
            $list[$key]['user'] = $value->user;
            $list[$key]['status'] = $this->getCouponStatus($value);
            $list[$key]['end_time'] = date("Y-m-d", $value['end_time']);
            $list[$key]['start_time'] = $value['start_time'] ? date("Y-m-d", $value['start_time']) : '随时可用';
        }
        $count = $this->where($where)->count();
        return ['count' => $count, 'list' => $list];
    }

    /**
     * 获取单条卡券
     * @param $where
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getCheckCoupon($where)
    {
        $coupon = $this->where($where)->findOrEmpty();
        if (!$coupon->isEmpty()) {
            $coupon = $this->formatCheckCoupon($coupon);
            return $coupon;
        } else {
            return false;
        }
    }

    /**
     * 格式化卡券
     * @param $value
     * @return mixed
     */
    public function formatCheckCoupon($coupon)
    {
        $coupon['user'] = $coupon->user;
        $coupon['status'] = $this->getCouponStatus($coupon);
        $coupon['end_time'] = date("Y-m-d", $coupon['end_time']);
        $coupon['start_time'] = $coupon['start_time'] ? date("Y-m-d", $coupon['start_time']) : '随时可用';
        return $coupon;
    }

    public function checkCouponStatus($coupon)
    {
        if (!$coupon) return ['code' => -1, 'msg' => '卡券不存在'];
        if ($coupon['state'] === 1) return ['code' => -1, 'msg' => '卡券已经被核销'];
        if ($coupon['end_time'] < time()) return ['code' => -1, 'msg' => '当前卡券已经过期'];
        return ['code' => 0, 'msg' => 'ok'];
    }

    //设置核销员组

    //内部方法

    public function getCouponStatus($value)
    {
        if ($value['state'] == 1) {
            //已核销
            return 1;
        }
        if ($value['state'] == 0 && $value['end_time'] >= time()) {
            //未核销
            return 0;
        }
        return -1;
    }

    //获取器

    public function getTypeNameAttr($value, $data)
    {
        $type_name = $value ?: $this->type_names[$data['type']];

        return $type_name ?: "默认卡券";
    }

    public function user()
    {
        return $this->hasOne(WechatUser::class, 'id', 'uid');
    }
}
